<?php

namespace App\Http\Controllers\Api\Goods;

use App\Http\Controllers\Controller;
use App\Libs\Strategy\Context;
use App\Models\Goods\Cates;
use App\Models\Goods\GoodSpecs;
use App\Models\Goods\Goods;
use App\Models\Goods\Specs;
use App\Models\Goods\SpecsItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class GoodsLogic extends Controller
{

    private $goods;

    public function __construct()
    {
        $this->goods = new Context(new Goods());
    }

    /**
     * 设置商品属性
     * post 为设置 get 为展示页面
    */
    public function attribute(Request $request){
        if($request->ajax())
        {
            $cateId = Str::after($request->cate_id,'/');
            //获取当前分类的所有规格
            $specs = Specs::where('cate_id',$cateId)->get(['id','name']);
            if($specs->isEmpty())
            {
                return $this->error('该分类没有设置规格');
            }
            $data = $specs->map(function($item){
                $item->id = $item->id;
                $item->name = $item->name;
                $item->sub = $item->items()->get(['id','item'])->map(function($key){
                    $key->id = $key->id;
                    $key->name = $key->item;
                    return $key;
                });
                return $item;
            });
            //获取当前商品的规格项目
            $specItem = self::getGoodsSpecs($this->goods->find($request->goods_id));
            return $this->success(['item'=>$specs->toJson(),'data'=>$specItem->toJson()]);
        }
        $goods = $this->goods->find($request->goods_id);
        $cates = self::getCate();
        $pcate = Cates::where('id',$goods->goods_cate_id)->value('pid');
        return view('goods.logic.attribute',compact('goods','cates','pcate'));
    }

    /**
     * 获取商品分类
     */
    public static function getCate()
    {
        return Cates::where('pid','=',0)->orderBy('sort','desc')->get(['id','cate_name'])->map(function($items){
            $items->value = $items->id;
            $items->label = $items->cate_name;
            $items->children = $items->ccate()->orderBy('sort','desc')->get()->map(function($item){
                $item->value = $item->id;
                $item->label = $item->cate_name;
                return $item;
            });
            return $items;
        });
    }

      /**
     * 获取商品规格价格
     */
    public static function getGoodsSpecs($goods)
    {
        if($goods->sepcs->isEmpty())
        {
            return collect([]);
        }
        $arr = [];
        foreach ($goods->sepcs as $k => $item) {
            $ids = explode('_', $item->item_id);
            foreach ($ids as $key => $id) {
                $arr[$k]['ids'][] = [
                    SpecsItem::find($id)->spec_id => $id
                ];
            }
            $arr[$k]['price'] = (float)$item->price;
            $arr[$k]['stock'] = (int)$item->stock;
            $arr[$k]['sku'] = $item->sku;
        }
        return collect($arr);
    }

    /**
     * 设置商品规格属性
     */
    public function setAttribute(Request $request){
        if($request->ajax())
        {
            $res = SpecsItem::where('id',$request->id)->update(['item'=>$request->value]);
            if($res)
            {
                return $this->success(['status'=>1,'message'=>'修改成功']);
            }
        }
        return $this->error('修改失败');
    }

    /**
     * 删除商品规格属性
     */
    public function deleteAttribute(Request $request)
    {
        if($request->ajax())
        {
            $res = SpecsItem::where('id',$request->id)->delete();
            if($res)
            {
                return $this->success(['status'=>1,'message'=>'删除成功']);
            }
        }
        return $this->error('删除失败');
    }

    /**
     * 更新商品规格属性
     */
    public function storeAttribute(Request $request)
    {

        if($request->ajax())
        {
            $res = SpecsItem::create(['item'=>$request->value,'spec_id'=>$request->spec_id]);
            if($res)
            {
                return $this->success(['status'=>1,'message'=>'添加成功']);
            }
        }
        return $this->error('添加失败');
    }

    public function storeGoodsAttribute(Request $request)
    {
        if($request->data)
        {

            //写入规格
            foreach ($request->data as $value) {
                $str = [];
                $ids = [];
                foreach ($value['ids'] as $key => $v) {
                    $id = array_values($v)[0];
                    $str[] = SpecsItem::where('id',$id)->value('item');
                    $ids[] = $id;
                }
                $itemId = implode('_', $ids);
                $itemName = implode('_',$str);
                GoodSpecs::updateOrCreate([
                    'goods_id' => $request->goods_id,
                    'item_id' => $itemId,
                ],[
                    'item_id' => $itemId,
                    'item_name' => $itemName,
                    'price' => $value['price'],
                    'stock' => $value['stock'],
                    'sku' => $value['sku'],
                    'goods_id' => $request->goods_id
                ]);
            }
            return $this->success(['status'=>1,'message'=>'设置规格成功']);
        }
        return $this->error('设置规格失败');
    }
}
